import React, { useEffect, useState } from 'react';
import './particlesBackground.less';

interface Particle {
  x: number;
  y: number;
  size: number;
  speedX: number;
  speedY: number;
  color: string;
  opacity: number;
}

const ParticlesBackground: React.FC = () => {
  const [particles, setParticles] = useState<Particle[]>([]);

  useEffect(() => {
    // 颜色数组
    const colors = [
      'rgba(79, 70, 229, 0.6)',  // 主色
      'rgba(129, 140, 248, 0.5)', // 次色
      'rgba(16, 185, 129, 0.4)',  // 绿色
      'rgba(59, 130, 246, 0.3)',  // 蓝色
    ];

    // 创建随机粒子
    const createParticles = () => {
      const windowWidth = window.innerWidth;
      const windowHeight = window.innerHeight;
      const newParticles: Particle[] = [];

      for (let i = 0; i < 40; i++) {
        newParticles.push({
          x: Math.random() * windowWidth,
          y: Math.random() * windowHeight,
          size: Math.random() * 6 + 1,
          speedX: Math.random() * 0.5 - 0.25,
          speedY: Math.random() * 0.5 - 0.25,
          color: colors[Math.floor(Math.random() * colors.length)],
          opacity: Math.random() * 0.5 + 0.1
        });
      }

      setParticles(newParticles);
    };

    // 更新粒子位置
    const updateParticles = () => {
      const windowWidth = window.innerWidth;
      const windowHeight = window.innerHeight;

      setParticles(prevParticles => 
        prevParticles.map(particle => {
          let newX = particle.x + particle.speedX;
          let newY = particle.y + particle.speedY;

          // 边界检测
          if (newX > windowWidth) newX = 0;
          else if (newX < 0) newX = windowWidth;
          
          if (newY > windowHeight) newY = 0;
          else if (newY < 0) newY = windowHeight;

          return {
            ...particle,
            x: newX,
            y: newY
          };
        })
      );
    };

    // 初始化粒子
    createParticles();

    // 设置动画更新间隔
    const animationInterval = setInterval(updateParticles, 50);

    // 窗口大小变化时重新创建粒子
    const handleResize = () => {
      createParticles();
    };

    window.addEventListener('resize', handleResize);

    return () => {
      clearInterval(animationInterval);
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return (
    <div className="particles-container">
      {particles.map((particle, index) => (
        <div
          key={index}
          className="particle"
          style={{
            left: `${particle.x}px`,
            top: `${particle.y}px`,
            width: `${particle.size}px`,
            height: `${particle.size}px`,
            backgroundColor: particle.color,
            opacity: particle.opacity,
          }}
        />
      ))}
    </div>
  );
};

export default ParticlesBackground; 